#pragma once
#include <iostream>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include "Logger.hpp"

const static int init_socketfd = -1;

using callback_t=std::function<std::string(const std::string &world)>;

class Server
{
public:
    Server(uint16_t port,callback_t cb)
        : _socketfd(init_socketfd), _port(port), _isrunning(false),_cb(cb)
    {
    }

    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket失败 " << _socketfd;
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket成功 " << _socketfd;
        struct sockaddr_in sev;
        bzero(&sev, sizeof(sev));
        sev.sin_family = AF_INET;
        sev.sin_port = htons(_port);
        sev.sin_addr.s_addr = htonl(INADDR_ANY);
        int n = bind(_socketfd, (sockaddr *)&sev, sizeof(sev));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind失败 " << _socketfd;
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind成功 " << _socketfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string world=buffer;
                std::string Resualt=_cb(world);
            }
        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~Server() {}

private:
    int _socketfd;
    uint16_t _port;
    bool _isrunning;

    callback_t _cb;
};